package com.rpay.web.filter;

import com.rpay.common.util.TraceIdGenerator;
import com.rpay.service.config.ServiceThreadLocal;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.MessageFormat;

/**
 * Title：
 * Description
 *
 * @author fxg06 on 2018/4/20
 * @version 1.0
 */
@Component
@WebFilter(urlPatterns = "/*")
public class ThreadLocalFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        MDC.put("requestUrl", MessageFormat.format("url={0}, method={1}", request.getRequestURL(), request.getMethod()));
        // 放入traceId
        MDC.put("traceId", TraceIdGenerator.getTraceId());


        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            MDC.clear();

            ServiceThreadLocal.removeAccessToken();
            ServiceThreadLocal.removeUserId();
        }
    }

    @Override
    public void destroy() {

    }
}
